(function(w) {
	var $ = w.jQuery;
	var tb_token = '';	
	var timestamp = (new Date()).valueOf();
	var url = 'http://pub.alimama.com/pubauc/searchAuctionList.json?&perPagesize=2&sort=_totalfee&toPage=1';
	
	/**
	*	轮询检测是否登陆，并获取tb_token
	*/
	
	chrome.cookies.get({url:'http://www.alimama.com',name:'_tb_token_'},function(cookie){
		tb_token = cookie.value;
		console.log(tb_token);
	});

	$("#searchBtn").bind('click',function()
	{
		var q=$('#keyword').val();					
		url +='&t='+timestamp+'&_tb_token_='+tb_token+'&q='+q;
		var html = '';
		$.getJSON(url,function(data){									
			$.each(data.data.pagelist,function(k,v){
				
				var clickurl = 'http://pub.alimama.com/common/code/getAuctionCode.json?auctionid='+v.auctionId;
				 clickurl+='&adzoneid=14998208&siteid=4068435&t='+timestamp+'&_tb_token_='+tb_token;
				var tbkclickurl='';				
							
				$.getJSON(clickurl,function(data){	
						tbkclickurl = data.data.clickUrl;
						html +='<tr><td><input type="checkbox" name="tbk['+v.auctionId+']" class="checkbox"></td>';
						html +='<td><a data-url="'+tbkclickurl+'" target="_blank"><img src="'+v.pictUrl+'" width="100" height="100"></a></td>';
						html +='<td><a data-url="'+tbkclickurl+'" target="_blank">'+v.title+'</a></td>';
						html +='<td>'+v.zkRate+'</td><td>'+v.zkPrice+'</td><td>'+v.commissionRatePercent+'%</td>';
						html +='<td>'+v.calCommission+'</td><td>'+v.totalNum+'</td><td>'+v.totalFee+'</td></tr>';
						$("#table").append(html);
				});	
			});
			var str = JSON.stringify(data);
			$("#tbjson").val(str);
				
		});	
	}
				
	);

/**
 * 绑定a标签的点击事件
 */
 $('body').on('click','a',function(e){
	var url = $(this).attr('data-url');
	chrome.tabs.create({
		url:url,
		active:true
	});
 }) 	
})(window);
